<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Frontend extends Controller_Template {
	
	public function before()
	{
		if ( ! Request::current()->is_ajax())
		{
			$this->template = 'frontend';
		}
		
		// logged as admin to backend
		$logged = FALSE;
		$admin = Kohana::$config->load('backend.admin');
		
		$cookie = array(
			'login' => Cookie::get('backend_login', NULL),
			'hash' => Cookie::get('backend_hash', NULL),
		);
		
		foreach ($admin as $login => $hash)
		{
			if ($cookie['login'] == md5($login) AND $cookie['hash'] == md5($hash))
				$logged = TRUE;
		}
		
		if ( ! $logged)
		{
			Cookie::delete('backend_login');
			Cookie::delete('backend_hash');
			Model_Reg::set('backend.login', FALSE);
		}
		else
		{
			Cookie::set('backend_login', $cookie['login']);
			Cookie::set('backend_hash', $cookie['hash']);
			Model_Reg::set('backend.login', $login);
		}
		
		// user auth from loginza.ru
		if (isset($_POST['token']) AND UTF8::strpos($_SERVER['HTTP_REFERER'], 'loginza.ru') !== FALSE)
		{
			$check = json_decode(file_get_contents('http://loginza.ru/api/authinfo?token='.$_POST['token']));
			
			if (isset($check->error_message))
			{
				View::set_global('msg_error', $check->error_message);
			}
			else
			{
				$identity = $check->identity;
				$identity_hash = md5($identity).md5(Kohana::$config->load('encrypt.default.key').$identity);
				$email = (isset($check->email)) ? $check->email : '';
				$photo = (isset($check->photo)) ? $check->photo : '';
				$first_name = (isset($check->name->first_name)) ? $check->name->first_name : '';
				$last_name = (isset($check->name->last_name)) ? $check->name->last_name : '';
				
				$user = ORM::factory('User')->where('identity', '=', $identity)->find();
				$user->identity = $identity;
				$user->identity_hash = $identity_hash;
				$user->email = $email;
				$user->photo = $photo;
				$user->first_name = $first_name;
				$user->last_name = $last_name;
				$user->save();
				
				Cookie::set('uIdentity', $identity_hash, 60 * 60 * 24 * 30);
				Request::current()->redirect('/');
			}
		}
		
		// prolongation uIdentity cookie
		if (($identity_hash = Cookie::get('uIdentity', FALSE)) AND $identity_hash !== FALSE)
		{
			Cookie::set('uIdentity', $identity_hash, 60 * 60 * 24 * 30);
		}
		
		$identity_hash = Cookie::get('uIdentity', FALSE);
		$user = ORM::factory('User')->where('identity_hash', '=', $identity_hash)->find();
		Model_Reg::set('user', $user);
		
		parent::before();
	}
	
}